﻿using System;
using System.Collections;
using System.Data;
using MySql.Data.Types;
using System.Collections.Generic;

namespace CzfSDK
{
	public static class DataTool
	{
		public static Hashtable Merge(this Hashtable oldT, Hashtable newT)
		{
            oldT = new Hashtable(oldT);
			foreach (var k in newT.Keys) 
			{
				if (oldT [k] is IList) {
                    var l = new ArrayList((IList)oldT[k]);
					if (newT [k] is IList) {
						foreach (var obj in (IList)newT[k]) {
							l.Add (obj);
						}
					}
                    oldT [k] = l.ToArray();
				} else {
					oldT [k] = newT [k];
				}
			}
			return oldT;
		}

		public static Hashtable ToHashtable(this DataRow dr)
		{
			var ht = new Hashtable (dr.Table.Columns.Count);
			foreach (DataColumn col in dr.Table.Columns) {
				var val = dr[col];
				if (val is MySqlDateTime) {
					val = ((MySqlDateTime)val).Value;
				}
				ht [col.ColumnName] = val;
			}
			return ht;
		}

		public static List<Hashtable> ToList(this DataTable dt)
		{
			var list = new List<Hashtable> (dt.Rows.Count);
			foreach (DataRow dr in dt.Rows) {
				list.Add(ToHashtable(dr));
			}
			return list;
		}
	}
}

